package com.jueyue.dao.factory;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.aop.framework.ProxyFactoryBean;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

import com.google.common.base.Strings;
import com.jueyue.dao.annotation.IDao;
import com.jueyue.dao.resource.SQLFileMap;
import com.jueyue.dao.util.ClassNameUtil;
import com.jueyue.dao.util.PackagesToScanUtil;

/**
 * 
 * @Title:MiniDaoHandler
 * @description:Init MiniDao Bean
 * @author 张代浩
 * @mail zhangdaiscott@163.com
 * @category www.jeecg.org
 * @date 20130817
 * @version V1.0
 */
public class MiniDaoBeanFactory implements BeanFactoryPostProcessor {
	private static final Logger logger = LoggerFactory
			.getLogger(MiniDaoBeanFactory.class);
	/** MiniDao扫描路径 */
	private List<String> packagesToScan;

	public void postProcessBeanFactory(
			ConfigurableListableBeanFactory beanFactory) throws BeansException {
		logger.debug("MiniDaoBeanFactory................ContextRefreshed...................");
		try {
			// 循环传入的MiniDao配置
			for (String pack : packagesToScan) {
				if (!Strings.isNullOrEmpty(pack)) {
					Class<?> miniDaoClass;
					for (String className : PackagesToScanUtil.getClasses(pack,
							".class")) {
						miniDaoClass = getClass(className);
						if (miniDaoClass != null
								&& miniDaoClass.isAnnotationPresent(IDao.class)) {
							// 单独加载一个接口的代理类
							ProxyFactoryBean proxyFactoryBean = new ProxyFactoryBean();
							proxyFactoryBean.setBeanFactory(beanFactory);
							proxyFactoryBean
									.setInterfaces(new Class[] { miniDaoClass });
							proxyFactoryBean
									.setInterceptorNames(new String[] { "miniDaoHandler" });
							String beanName = ClassNameUtil
									.getInterRealName(miniDaoClass
											.getName()
											.substring(
													miniDaoClass.getName()
															.lastIndexOf(".") + 1));
							if (!beanFactory.containsBean(beanName)) {
								logger.info("MiniDao Interface [/"
										+ miniDaoClass.getName()
										+ "/] onto Spring Bean '" + beanName
										+ "'");
								beanFactory.registerSingleton(beanName,
										proxyFactoryBean.getObject());
							}
						}
					}

				}
				// 扫描所以的sql加载到内存中
				new SQLFileMap().scanClassPathFiles((Object[]) packagesToScan
						.toArray());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	private Class<?> getClass(String className) {
		try {
			className = className.substring(0, className.length() - 6);
			// 判断是否是以点开头
			if (className.startsWith(".")) {
				className = className.replaceFirst(".", "");
			}
			return Thread.currentThread().getContextClassLoader()
					.loadClass(className);
		} catch (ClassNotFoundException e) {
			logger.error("添加用户自定义视图类错误 找不到此类的.class文件");
			e.printStackTrace();
		}
		return null;
	}

	public void setPackagesToScan(List<String> packagesToScan) {
		this.packagesToScan = packagesToScan;
	}

}
